package jsyf.oa.web.socket;

import java.util.ArrayList;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;



/**
 * Created by Administrator on 2018/7/23 0023.
 */
@Component
public class MyWebSocketHandler implements WebSocketHandler {


    private static final Logger log = Logger.getLogger(MyWebSocketHandler.class);

    // 保存所有的用户session
    private static final ArrayList<WebSocketSession> users = new ArrayList<WebSocketSession>();

    // 连接 就绪时
    @Override
    public void afterConnectionEstablished(WebSocketSession session)
            throws Exception {

        log.info("connect websocket success.......");

        users.add(session);

    }


    // 处理页面发来的信息
    @Override
    public void handleMessage(WebSocketSession session,
                              WebSocketMessage<?> message)  {


    }


    // 处理传输时异常
    @Override
    public void handleTransportError(WebSocketSession session,
                                     Throwable exception) throws Exception {
        // TODO Auto-generated method stub

    }


    // 关闭 连接时
    @Override
    public void afterConnectionClosed(WebSocketSession session,
                                      CloseStatus closeStatus) throws Exception {

        log.info("connect websocket closed.......");

        users.remove(session);

    }


    @Override
    public boolean supportsPartialMessages() {
        // TODO Auto-generated method stub
        return false;
    }


    // 给所有用户发送 信息
    public void sendMsgToAllUsers(TextMessage textMessage) throws Exception {

        for (WebSocketSession user : users) {
            user.sendMessage(textMessage);
        }

    }
}
